<script setup lang="ts">
import carouselImageService from '@/api/modules/carouselImage/carouselImage.ts'
import productService from '@/api/modules/product'
import toolService from '@/api/modules/tool'
import LoginPrompt from '@/components/LoginPrompt/LoginPrompt.vue'
import useUserStore from '@/store/modules/user.ts'

const current = ref<number>(0)
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const swiperList = ref([])

// curtain
const curtainImg = ref<string>('https://i.mji.rip/2025/07/11/98e9f7bcd62237cebee2c5c8b11efc2c.png')
const curtainShow = ref(false)

const scrollLeft = ref<number>(0)
const noLoginShow = ref(false)

// 产品列表
const productList = ref([])
// 固定产品列表
const fixedProductList = ref([])

onLoad(() => {
  const token = getToken()
  if (token) {
    const firstRechargeRecord = userInfo?.value?.firstRechargeRecord
    console.log(firstRechargeRecord)
    if (firstRechargeRecord) {
      curtainShow.value = true
    }
  }
})

onShow(() => {
  getCarouselImageList()
  getMobileProductList()
})

function bgClass(type) {
  switch (type) {
    case 'lemonQueryAccident':
      return 'bg-[#EBEEFF]'
    case 'cheXinMengQueryAccident':
      return 'bg-[#FFEDD2]'
    case 'uCarPreciseQuery':
      return 'bg-[#E8F9F1]'
    default:
      return 'bg-[#F2F2F2]'
  }
}

// 默认描述映射（可随需求扩展）
function defaultDesc(type) {
  switch (type) {
    case 'lemonQueryAccident':
      return '出险速办，赔付零时差'
    case 'cheXinMengQueryAccident':
      return '车险秒响应，快赔无忧'
    case 'uCarPreciseQuery':
      return '精准维保，一键查询'
    default:
      return '专业服务，安心无忧'
  }
}
function adTitleClass(type) {
  switch (type) {
    case 'lemonQueryAccident':
      return 'ad-title-one'
    case 'cheXinMengQueryAccident':
      return 'ad-title-two'
    case 'uCarPreciseQuery':
      return 'ad-title-three'
    default:
      return 'ad-title-default'
  }
}

function getCarouselImageList() {
  carouselImageService.mobileList({}).then((res) => {
    console.log(res)
    const data = res.data.carouselImageMobileListVos
    swiperList.value = data.map(item => item.fileUrl)
  })
}

function getMobileProductList() {
  productService.mobileList().then((res) => {
    const data = res.data
    const {
      productMobileListVos,
    } = data
    const positiveFix = productMobileListVos.filter(item => item.fixFlag === 1)
    const negativeFix = productMobileListVos.filter(item => item.fixFlag === -1)
    const desiredOrder = ['U车查维保', 'U车精准查询', '云端查调表', '电池报告']
    const positiveFixOrder = ['车信盟查出险', '柠檬查出险']
    productList.value = negativeFix.sort((a, b) => {
      return desiredOrder.indexOf(a.productName) - desiredOrder.indexOf(b.productName)
    })
    fixedProductList.value = positiveFix.sort((a, b) => {
      return positiveFixOrder.indexOf(a.productName) - positiveFixOrder.indexOf(b.productName)
    })
  })
}

function navigateTo(url: string, price?: string, productUuid?: string, type?: string, typeName?: string) {
  const token = getToken()
  if (!token) {
    noLoginShow.value = true
    return
  }
  uni.navigateTo({
    url: url + (price ? `?price=${price}&productUuid=${productUuid}&productType=${type}&productTypeName=${typeName}` : ''),
  })
}

function handlePreviewFile() {
  uni.showLoading({
    title: '文件加载中...',
  })
  toolService.mobileList().then((res) => {
    console.log(res)
    if (res?.data) {
      const fileData = res.data[0]
      const pathname = decodeURIComponent(fileData.fileUrl) // 解码 URL，处理中文
      const lastSegment = pathname.split('/').pop() // 获取文件名部分
      const fileType = lastSegment.includes('.') ? lastSegment.split('.').pop() : ''
      const url = fileData.fileUrl
      uni.downloadFile({
        url,
        filePath: `${wx.env.USER_DATA_PATH}/` + `购车合同.${fileType}`,
        success(res) {
          const filePath = res.filePath
          uni.openDocument({
            filePath,
            showMenu: true,
            success(res) {
              console.log(res)
              uni.hideLoading()
            },
            fail(res) {
              console.log(res)
              uni.hideLoading()
            },
          })
        },
        fail(res) {
          console.log(res)
          uni.hideLoading()
        },
      })
    }
  })
}
</script>

<template>
  <div class="home-container bg-[#F5F6F9]">
    <div class="swiper-container relative">
      <wd-swiper v-if="swiperList.length > 0" v-model:current="current" :list="swiperList" autoplay :show-controls="false" :height="270" :indicator="false" />
    </div>
    <div class="relative top-[-11px] rounded-tl-2xl rounded-tr-2xl bg-[#F5F6F9] px-2 pb-25">
      <div class="grid grid-cols-2 pt-6" style="margin-bottom: 18.75rpx;">
        <div
          v-for="(item, index) in fixedProductList"
          :key="item.id"
          class="flex flex-col items-center justify-center rounded-lg p-2"
          :class="bgClass(item.productType)"
          :style="index === 0 ? 'margin-right: 18.75rpx' : ''"
          @click="navigateTo('/pages/orderSearch/index', item.productPrice, item.productUuid, item.productType, item.productTypeDict)"
        >
          <div
            class="ad-title ShuHeiTi-text text-[18px] font-bold"
            :class="adTitleClass(item.productType)"
          >
            {{ item.productTypeDict }}
          </div>

          <!-- 描述：有 remark 用 remark，没 remark 用默认文案 -->
          <span class="ad-desc mt-2 text-[12px] text-[#666]">
            {{ defaultDesc(item.productType) }}
          </span>
        </div>
      </div>

      <div class="rounded-lg bg-white" style="margin-bottom: 18.75rpx;">
        <div class="home-card-title rounded-lg p-3 pb-0 text-[18px] text-[#333] font-bold">
          U车查询
        </div>
        <div class="grid grid-cols-2 gap-1">
          <div v-for="product in productList" :key="product.id" class="flex flex-col p-2" @click="navigateTo('/pages/orderSearch/index', product.productRealPrice || product.productPrice, product.productUuid, product.productType, product.productTypeDict)">
            <div class="mx-auto max-w-300 w-full overflow-hidden rounded-md">
              <image
                :src="product.imageUrl"
                alt="产品图片"
                class="aspect-[2/1] w-full object-contain"
                mode="scaleToFill"
                style="height: 160rpx"
              />
            </div>
            <div class="mt-2 text-base text-gray-800 font-bold">
              {{ product.productTypeDict }}
            </div>
            <div class="mt-1 text-base text-red-500 font-600">
              <!--              {{ product.productPrice }}元 起 -->
              {{ product.productRealPrice === 0 ? `${product.productPrice}元 起` : ` ${product.productRealPrice} 元` }}
            </div>
          </div>
        </div>
        <!--        <div class="bg-white divide-x-4 divide-y-4"> -->
        <!--          <div class="grid grid-cols-2 gap-4 p-4"> -->
        <!--            <div v-for="product in productList" :key="product.id" class="flex flex-col bg-white rounded-lg shadow p-2"> -->
        <!--              <div class="aspect-square overflow-hidden rounded-md"> -->
        <!--                <img -->
        <!--                  :src="product.imageUrl" -->
        <!--                  alt="产品图片" -->
        <!--                  class="w-full h-full object-cover transition-transform hover:scale-105" -->
        <!--                /> -->
        <!--              </div> -->
        <!--              <div class="mt-2 text-sm text-gray-800 font-medium"> -->
        <!--                {{ product.productTypeDict }} -->
        <!--              </div> -->
        <!--              <div class="text-red-500 text-xs mt-1"> -->
        <!--                {{ product.productPrice }}元 起 -->
        <!--              </div> -->
        <!--            </div> -->
        <!--          </div> -->
        <!--          <div -->
        <!--            v-for="(item) in productList" -->
        <!--            :key="item.id" -->
        <!--            class="flex cursor-pointer px-4 py-3 product-item" -->
        <!--            @click="navigateTo('/pages/orderSearch/index', item.productPrice, item.productUuid, item.productType)" -->
        <!--          > -->
        <!--            <div class="flex-1 pr-4"> -->
        <!--              <h2 class="line-clamp-2 mb-2 text-base font-700 tracking-normal"> -->
        <!--                {{ item.productName }} -->
        <!--              </h2> -->
        <!--              <div class="mb-3 flex gap-2"> -->
        <!--                <span -->
        <!--                  class="rounded-full px-3 py-1 text-xs" :class="[ -->
        <!--                    item.productTypeDict === '柠檬查出险' ? 'bg-yellow-50 text-yellow-600' : 'bg-blue-50 text-blue-600', -->
        <!--                  ]" -->
        <!--                > -->
        <!--                  {{ item.productTypeDict }} -->
        <!--                </span> -->
        <!--              </div> -->
        <!--              <div class="text-xl text-red-500 font-semibold tracking-widest"> -->
        <!--                {{ item.productPrice }}元起 -->
        <!--              </div> -->
        <!--            </div> -->
        <!--            <div class="h-24 w-28 flex-shrink-0 overflow-hidden rounded-lg"> -->
        <!--              <img -->
        <!--                :src="item.imageUrl" -->
        <!--                class="h-full w-full object-cover object-top" -->
        <!--              > -->
        <!--            </div> -->
        <!--          </div> -->
        <!--        </div> -->
        <!--        <scroll-view -->
        <!--          class="scroll-x-container mt-3" -->
        <!--          scroll-y -->
        <!--          :scroll-left="scrollLeft" -->
        <!--        > -->
        <!--          <div -->
        <!--            v-for="item in queryList" -->
        <!--            :key="item.id" -->
        <!--            class="item" -->
        <!--          > -->
        <!--            <div class="w-full flex flex-col justify-center" @click="navigateTo('/pages/orderSearch/index', item.price)"> -->
        <!--              <wd-img :src="item.img" :width="100" :height="100" /> -->
        <!--              <div class="mt-2 text-[16px] text-[#333] font-bold"> -->
        <!--                {{ item.name }} -->
        <!--              </div> -->
        <!--              <div class="line-clamp-1 mt-1 text-[18px] text-[#ee0a24FF] font-bold"> -->
        <!--                {{ formatPrice(item.price, { withSymbol: true, returnString: true }) }} -->
        <!--                <span class="ml-1 text-sm">起</span> -->
        <!--              </div> -->
        <!--            </div> -->
        <!--          </div> -->
        <!--        </scroll-view> -->
      </div>
      <div class="rounded-lg bg-white">
        <div class="home-card-title rounded-lg p-3 pb-0 text-[18px] text-[#333] font-bold">
          工具
        </div>
        <div class="p-3">
          <div class="rounded-lg bg-[#F9F9F9] p-3" @click="handlePreviewFile">
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <img src="@/static/svg/contractDownload.svg" class="h-10 w-10">
                <div class="ml-3">
                  <div class="text-[16px] text-[#333] font-bold">
                    车辆信息交易合同
                  </div>
                  <div class="mt-1 text-[12px] text-[#666]">
                    点击此处下载车辆交易合同
                  </div>
                </div>
              </div>
              <wd-icon name="arrow-right" size="25px" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <wd-curtain v-model="curtainShow" :src="curtainImg" :width="280" close-position="bottom" :z-index="9999" to="/pages/recharge/index" />
  <login-prompt v-model="noLoginShow" />
</template>

<style lang="scss" scoped>
.home-container{
  height: calc(100vh - 50px - 40px);
}
.ad-title{
  position: relative;
  &::before{
    content: "";
    bottom: -2px;
    position: absolute;
    left: 0;
    width: 100%;
    height: 10px;
    opacity: 0.5;
    border-radius: 5px;
  }

  &.ad-title-one::before {
    background: #B8BEFB;
  }

  &.ad-title-two::before {
    background: #FFDA9A;
  }
}

.scroll-x-container {
  white-space: nowrap;
  width: 100%;
  height: 330rpx;
}

.item {
  display: inline-block;
  justify-content: center;
  width: 230rpx;
  height: 330rpx;
  //line-height: 100rpx;
  //text-align: center;
  //background-color: #4fc08d;
  //color: #fff;
  border-radius: 10rpx;
}

.home-card{
  background: linear-gradient( 180deg, #FFEED3 0%, #FFFDFA 22%, #FFFFFF 100%);
  .home-card-title{
  }
}

.noLogin-card{
  background: linear-gradient(177.32deg, rgba(165, 201, 255, 0.43) 0%, rgba(247, 192, 255, 0) 40.57%, rgba(163, 242, 255, 0) 100%);
}

.home-container{
  padding-bottom: 180rpx;
}

.product-item{
  border-bottom: 1px solid #eee;
  &:last-child{
    border-bottom: none;
  }
}
.swiper-container{
  :deep(.wd-swiper__track){
    border-radius: 0 !important;
  }
}
</style>

<route type="home" lang="json">
</route>
